﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using G.SL.Navigate;
using G.SL.Controls;
using System.IO;

namespace G.APITest.Views
{
    public partial class CreateClassPage : GBasePage
    {
        public CreateClassPage()
        {
            InitializeComponent();
            //文件
            MenuItem item1 = new MenuItem() { Name = "文件" };
            item1.Items.Add(new MenuItem() { Name = "打开json文件", Command = new SL.MVVM.CallBackCommand(OpenJsonFile) });
            item1.Items.Add(new MenuItem() { Name = "添加json数据", Command = new SL.MVVM.CallBackCommand(AddJsonData) });
            PageMenuService.GetMenu(this).Add(item1);
            cboClassType.ItemsSource = Enum.GetValues(typeof(Data.ClassType));
            if (System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Contains("ClassType"))
            {
                cboClassType.SelectedItem = (Data.ClassType)System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings["ClassType"];
            }
            else
                cboClassType.SelectedIndex = 0;
            //保存
            //MenuItem item2 = new MenuItem() { Name = "保存" };
            //item2.Items.Add(new MenuItem() { Name = "独立存储", Command = new SL.MVVM.CallBackCommand(SaveToIsolate) });
            //item2.Items.Add(new MenuItem() { Name = "另存为", Command = new SL.MVVM.CallBackCommand(SaveAs) });
            //PageMenuService.GetMenu(this).Add(item2);
        }


        private void OpenJsonFile(object p)
        {
            OpenFileDialog open = new OpenFileDialog();
            if (open.ShowDialog() == true)
            {
                try
                {
                    using (var fileStream = open.File.Open(System.IO.FileMode.Open, System.IO.FileAccess.Read))
                    {
                        try
                        {
                            this.CreatTree(fileStream.ReadToEnd(), "Root");
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("JSOn文件出错，请使用正确的json文件！\r\n" + ex.Message);
                        }
                    }
                }
                catch (FieldAccessException ex)
                {
                    MessageBox.Show("只能读取文档下面的文件！");
                }
            }
        }

        private void AddJsonData(object p)
        {
            G.APITest.ChildWindows.AddJsonDataChildWindow jsonchild = new G.APITest.ChildWindows.AddJsonDataChildWindow();
            jsonchild.Closed += (s, d) =>
            {
                if (jsonchild.DialogResult == true)
                {

                    this.CreatTree(jsonchild.JosnString, jsonchild.JosnName);
                }
            };
            jsonchild.Show();
        }

        private void CreatTree(string strJson, string strJsonName = "Root")
        {
            try
            {
                System.Json.JsonValue value = System.Json.JsonObject.Parse(strJson);
                var node = new Data.CreateClassTreeNode() { Key = "Root" };
                InitialJson(value, node);
                treeView.ItemsSource = new Data.CreateClassTreeNode[] { node };
            }
            catch (Exception ex)
            {
                throw new Exception("json文件有错误，请确保Json文件格式正确！", ex);
            }
        }

        private void InitialJson(System.Json.JsonValue value, Data.CreateClassTreeNode node)
        {
            node.Value = value;
            if (value == null)
            {
                node.JsonType = System.Json.JsonType.String;
                return;
            }
            node.JsonType = value.JsonType;
            switch (value.JsonType)
            {
                case System.Json.JsonType.Object:
                    foreach (KeyValuePair<string, System.Json.JsonValue> key in value)
                    {
                        var n = new Data.CreateClassTreeNode() { Key = key.Key };
                        InitialJson(key.Value, n);
                        node.Nodes.Add(n);
                    }
                    break;
                case System.Json.JsonType.Array:
                    var array = value as System.Json.JsonArray;
                    if (array.Count > 0)
                    {
                        var v = array[0];
                        if (v.JsonType == System.Json.JsonType.Object)
                        {
                            foreach (KeyValuePair<string, System.Json.JsonValue> key in v)
                            {
                                var n = new Data.CreateClassTreeNode() { Key = key.Key };
                                InitialJson(key.Value, n);
                                node.Nodes.Add(n);
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }


        // 当用户导航到此页面时执行。
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (this.NavigationContext.Param != null)
            {
                this.CreatTree(this.NavigationContext.Param as string);
            }
        }

        private void treeView_SelectedItemChanged_1(object sender, RoutedPropertyChangedEventArgs<object> e)
        {

        }

        private void treeView_Drop_1(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                FileInfo[] files = (FileInfo[])e.Data.GetData(DataFormats.FileDrop);
                if (files.Length > 1)
                {
                    MessageBox.Show("只能拖取一个文件");
                    return;
                }
                foreach (var item in files)
                {
                    using (var fileStream = item.Open(System.IO.FileMode.Open, System.IO.FileAccess.Read))
                    {
                        try
                        {
                            this.CreatTree(fileStream.ReadToEnd(), "Root");
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("JSOn文件出错，请使用正确的json文件！\r\n" + ex.Message);
                        }
                    }
                }

            }
        }

        private void cboClassType_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            if (cboClassType.SelectedIndex != -1)
            {
                Data.CreateClassTreeNode.ClassType = (Data.ClassType)cboClassType.SelectedItem;
                var source = treeView.ItemsSource;
                treeView.ItemsSource = null;
                treeView.ItemsSource = source;
                System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings["ClassType"] = Data.CreateClassTreeNode.ClassType;
                System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Save();
            }
        }
    }
}
